library(plotly)
plot_ly(mtcars, x=mtcars$wt, y= mtcars$mpg, mode="markers")
Basic Scatterplot
library(plotly)
## Warning: package 'plotly' was built under R version 4.0.2
plot_ly(mtcars, x= mtcars$wt, y= mtcars$mpg, mode="markers")
Scatterplot Color
plot_ly(mtcars, x= mtcars$wt, y= mtcars$mpg, mode="markers", color = as.factor(mtcars$cyl))
## No trace type specified:
## Based on info supplied, a 'scatter' trace seems appropriate.
## Read more about this trace type -> https://plot.ly/r/reference/#scatter
Continuous Color
plot_ly(mtcars, x= mtcars$wt, y= mtcars$mpg, mode="markers", color = mtcars$disp)
Scatterplot Sizing
plot_ly(mtcars, x= mtcars$wt, y= mtcars$mpg, mode="markers",
color = as.factor(mtcars$cyl), size = mtcars$hp) #horse power: every point will have different size
3D Scatterplot
set.seed(2020-08-06)
temp <- rnorm(100, mean=30, sd=5)
pressue <- rnorm(100)
dtime <- 1:100
plot_ly(x=temp, y=pressue, z=dtime,
type = "scatter3d", mode="markers", color = temp)
Line Graoh
data("airmiles")
plot_ly(x=time(airmiles), y=airmiles)
Multi Line Graoh
library(plotly)
library(tidyr) # swtich from short to long data format
library(dplyr) # working with dataframe
data("EuStockMarkets")
stocks <- as.data.frame(EuStockMarkets) %>%
gather(index, price) %>%
mutate(time = rep(time(EuStockMarkets),4))
plot_ly(stocks, x=stocks$time, y=stocks$price, color = stocks$index)
Other types of plots
## Histogram
plot_ly(x=precip, type = "histogram")
## Boxplot
plot_ly(iris, y=iris$Petal.Length, color = iris$Species, type = "box")
## Heatmap
terrain1 <- matrix(rnorm(100*100), nrow = 100, ncol = 100)
plot_ly(z=terrain1, type = "heatmap")
## 3D Surface
terrain2 <- matrix(sort(rnorm(100*100)), nrow=100, ncol=100)
plot_ly(z=terrain2, type = "surface")
Choropleth Maps
# create data frame
state_pop <- data.frame(State=state.abb, Pop=as.vector(state.x77[,1]))
# Create hover text
state_pop$hover <- with(state_pop, paste(State, '<br>', "Population:", Pop))
# make state borders red
borders <- list(color=toRGB("red"))
# Set up some mapping options
map_options <- list(
scope = "usa",
projection = list(type='albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)
plot_ly(state_pop, z= state_pop$Pop, text= state_pop$hover, locations=state_pop$State, type = 'choropleth', locationmode = 'USA-states',
color = state_pop$Pop, colors = 'Blues', marker=list(line=borders)) %>%
layout(title= 'US Population in 1975', geo=map_options)
plotly and ggplot
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000),]
p <- ggplot(data = d, aes(x=carat, y=price)) + geom_point(aes(text=paste("Clarity:", clarity)), size=4) +
geom_smooth(aes(colour = cut, fill = cut)) + facet_wrap(~cut)
## Warning: Ignoring unknown aesthetics: text
(gg <- ggplotly(p))
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
ggplotly(p)
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'